<script>
	var strTestData = '';
	var selected = [];
	
	jQuery(document).ready(function(){
		$( "#template_name" ).combogrid({
			url: 'modules.php?file=fetch_server&type=fetch&action=case_paper',
			debug:true,
			//replaceNull: true,
			colModel: [{'columnName':'id','width':'10','label':'Id'}, {'columnName':'name','width':'60','label':'Full Name'},{'columnName':'case_paper_id','width':'30','label':'Case Paper Id'}],
			select: function( event, ui ) {
				$( "#patient_details" ).val( ui.item.name );
				$( "#patient_id" ).val( ui.item.id );
				$( "#case_paper_id" ).val( ui.item.case_paper_id );
				return false;
				}
		});
	});

	function check_box( obj ) {

		//If you want to send the content by click then need to add in the checkbox input type this function o the click.
		//check_box( $(this) );
		if( obj.is(":checked") ) {
			strTestData += obj.closest( 'tr' ).find("td").eq(4).text();
			selected.push( obj.closest( 'tr' ).find("td").eq(4).text() );
		} else {
			selected.pop( obj.index() );
		}

		console.log( selected );
	}

	function setData() {

		var strDivId = $('#div_id_name').val();
		var intCount = 0;
		
		//$('#template_check input:checkbox:checked').each( function() {
		$('input[type=checkbox]').each( function() {
			if( $(this).is(":checked") ) {
				intCount++;	
				strTestData += $(this).closest( 'tr' ).find("td").eq(4).text();

				if( intCount >= 1 ) strTestData += ",\n";
			}
		});

		if( "investigation" == strDivId.toLowerCase() ) {
			strTestData = getInvestigation();
			strTestData = strTestData.replace( /,/g, ',\n' )
		}

		if( strTestData != '' && strTestData != null ) {
			$('#' + strDivId ).text( strTestData );

			removeDiv( divPopupContainer );
			removeDiv( divLightBox );
		} else {
			alert( "Please select master template to to submit." );
		}
	}

	function getInvestigation() {
		var new_array = [];
		$('input[type=checkbox]').each( function() {
			if( $(this).is(":checked") ) {
				strString = $(this).closest( 'tr' ).find("td").eq(4).text();
				arrData = strString.split(',');
				for( var i = 0; i < arrData.length; i++ ) {
					new_array.push( arrData[i].replace( '\n', '' ) );
				}
			}
		});

		var clean_array = removeDuplicates( new_array );

		console.log( clean_array );

		return clean_array.toString();
	}

	function removeDuplicates( array ) {
		var new_array = [];
		for( var i=0; i<array.length; i++ ) {
			// convert current sentence to sorted, lowercase string
			var sen = array[i].split(" ").sort().join(" ");
			if( new_array.indexOf( sen.toLowerCase() ) == -1 ) {
				new_array.push( sen );
			}
		}

		return new_array;
	}

	Array.prototype.indexOf = function( item, optional_start_index ) {
		for(var i = optional_start_index || 0; i < this.length; i++ ) {
			if( this[i].toLowerCase() == item ) return i;
		}
		return -1;
	}
	
</script>

<style>
#divViewContainer {
	font: 10px verdana,sans-serif;
	height: 70%;
	margin-left: 20%;
	margin-right: 10%;
	margin-top: 10%;
	padding: 10px;
	position: fixed;
	overflow-y: scroll;
	top: 45%;
	width: 70%;
	z-index: 4;
}
</style>

<script>
	$(document).ready(function() {
		$('#dataTables-example').dataTable();
	});
</script>
<?php

autoLoader();

if( true == isset( $_GET['template_type_id'] ) && true == valStr( $_GET['template_type_id'] ) ) {
	fetchById();
	exit;
	
}

if( true == isset( $_GET['patient_name'] ) && true == valStr( $_GET['patient_name'] ) ) {
	fetchByName();
	exit;
}

function fetchById( $intTempalteTypeId = NULL ) {
	$objTemplateMaster = new TemplateMaster();
	
	$intTempalteTypeId = ( true == valStr( $intTempalteTypeId ) ) ? $intTempalteTypeId : $_GET['template_type_id'];
	
	$strSql = 'SELECT * FROM template_masters WHERE template_type_id = ' . $intTempalteTypeId . ';';
	
	$arrobjTemplateMasters = $objTemplateMaster->fetchSql( $strSql );
?>
	<div>
	<table class="table table-striped table-bordered table-hover" id="dataTables-example">
		<thead class="thclass" style="font-size: 10px;">
			<tr>
				<th>S/N</th>
				<th>Name</th>
				<th>Descrition</th>
				<th>Doctor Id</th>
				<th>Data</th>
			</tr>
		</thead>
		<tbody class="tbclass" style="font-size: 10px;">
<?php
	if( true == valArr( $arrobjTemplateMasters ) ) {
		foreach( $arrobjTemplateMasters as $objTemplateMaster ) {
			$strHtmlData .= '<tr><td align=center><input type=checkbox value=' . $objTemplateMaster->getId() . ' name=template id=template_check></td><td>' . $objTemplateMaster->getName() . '</td><td>' . $objTemplateMaster->getDescription() . '</td><td>' . $objTemplateMaster->getCreatedBy() . '</td><td>' . $objTemplateMaster->getData() . '</tr>';
		}
	}

	echo $strHtmlData;
?>
			</tbody>
		</table>
	</div>
	<hr/>
	<div>
		<input type="hidden" id="div_id_name" name="div_id" value="<?php echo ( true == valStr( $_GET['div_id'] ) ) ? $_GET['div_id'] : ''; ?>" />
		<input type="button" name="select" value="..SELECT.." onclick="setData();" style="font-size: 14px;" />
		<input type="button" name="Cancel" value="..CANCEL.." style="font-size: 14px;" onclick="JavaScript: removeDiv( divPopupContainer );removeDiv( divLightBox );" />
	</div>
	
<?php
	exit;
}

function fetchByName( $strPatientName = NULL ) {
	$objPatient = new Patients();
	
	$strPatientName = ( true == valStr( $strPatientName ) ) ? $strPatientName : $_GET['patient_name'];
	
	$arrstrName = explode( ' ', $strPatientName );
	
	$strFirstName 	= getArrayElementByKey( 0, $arrstrName );
	$strLastName 	= getArrayElementByKey( 1, $arrstrName );
	
	$strSql = 'SELECT * FROM PATIENTS WHERE first_name = \'' . $strFirstName . '\' AND last_name = \'' . $strLastName . '\'';
	$arrobjPatients = $objPatient->fetchSql( $strSql );
	
	$arrobjAllPatients = array();
	
	if( true == valArr( $arrobjPatients ) ) {
		foreach( $arrobjPatients as $objPatient ) {
			$strName = $objPatient->getFirstName() . ' ' . $objPatient->getLastName();
			$arrobjAllPatients[strtolower( $strName )] = $objPatient;
		}
	}
	
	$strName = $strFirstName . ' ' . $strLastName;
	$objPatient = getArrayElementByKey( strtolower( $strName ), $arrobjAllPatients );
	
	if( true == valObj( $objPatient, 'BasePatients' ) ) {
		$intCasePaperId = findCasePaperId( $objPatient->getId() );
	
		echo $objPatient->getId() . '_' . $objPatient->getFirstName() . '_' . $objPatient->getLastName() . '_' . $intCasePaperId;
		exit;
	} else {
		echo 'not found::';
		exit;
	}
	exit;
}

function findCasePaperId( $intPatientId ) {
	if( false == valStr( $intPatientId ) ) return NULL;
	
	$objConnection = new Patients();
	
	$strSql = 'SELECT max( id ) as id FROM case_papers WHERE patient_id = ' . $intPatientId;
	$result = $objConnection->connection->RunQuery( $strSql );
	
	$intCasePaperId = NULL;
	if( true == $result ) {
		while( $row = $result->fetch_array( MYSQLI_ASSOC ) ) {
			$intCasePaperId = $row['id'];
		}
	}
	
	return $intCasePaperId;
}

echo 'not found::';
exit;
?>